﻿//==============================================================================================
//Author: Uncle Song
//Create Date: 2022-07-26
//Description: 网格扩展方法
//----------------------------------------------------------------------------------------------
//Alter History:
//              2022-07-26  add 网格区域创建
//============================================================================================== 
using UnityEngine;

namespace FrameWorkSong
{
    public static class MeshExtention
    {
        /// <summary>
        /// 创建正方形面
        /// </summary>
        /// <param name="size">尺寸</param>
        /// <param name="num">细分</param>
        /// <returns></returns>
        public static Mesh CreateSquareArea(this Mesh mesh ,float size,int num)
        {
            //一共多少行/列
            int ranks = 2 * num + 1;
            int pointsCount = ranks * ranks;
            Vector3[] meshPoints = new Vector3[pointsCount];
            int[] triangles = new int[24 * num * num];
            Vector2[] uvs = new Vector2[pointsCount];
            float halfSize = size * 0.5f;
            //左下角角点
            Vector3 cornerPoint = new Vector3(-halfSize, 0, -halfSize);
            //距离单位偏移
            float unitSize = size / (num * 2);
            //距离单位偏移X
            Vector3 unitVec_x= new Vector3(unitSize, 0, 0);
            //距离单位偏移Z
            Vector3 unitVec_z = new Vector3(0, 0, unitSize);
            //UV单位偏移
            float unitUV = 1.00f / (num * 2.00f);
            //UV单位偏移X
            Vector2 uvVec_x = new Vector2(unitUV, 0);
            //UV单位偏移Y
            Vector2 uvVec_y = new Vector2(0,unitUV);
            int k = 0;
            for (int i = 0; i < ranks; i++)
            {
                for (int j = 0; j < ranks; j++)
                {
                    meshPoints[i* ranks+ j] = cornerPoint + j * unitVec_x + i * unitVec_z;
                
                    uvs[i * ranks + j] = j * uvVec_x + i * uvVec_y;
                   
                    if (i < ranks-1&& j < ranks-1)
                    {
                        triangles[k] = (i * ranks) + j+1;
                        triangles[k + 1] = (i * ranks) + j;
                        triangles[k + 2] = ((i + 1) * ranks) + j;
                        triangles[k + 3] = (i * ranks) + j+1;
                        triangles[k + 4] = ((i + 1) * ranks) + j;
                        triangles[k + 5] = ((i + 1) * ranks) + j+1;
                        k += 6;
                    }
                }
            }
            mesh.vertices = meshPoints;
            mesh.triangles = triangles;
            mesh.uv = uvs;
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();
            return mesh;
        }
    }
}
